Exercise 11: Find The Vowels

Directions

Write a function that returns the number of vowels used in a string. Vowels are the characters 'a', 'e', 'i', 'o', and 'u'.

Examples

vowels('Hi There!') --> 3
  vowels('Why do you ask?') --> 4
  vowels('Why?') --> 0

Guidelines

Two solutions:

1. Iteractive

  • discuss use of string or array as a variable
  • Array.prototype.includes()

2. Regular expression

  • use String.prototype.match()
  • use ternary expression
  • handle what match() returns
    • if no match found, return null (falsey)
    • if match found, return an array of all matches

Solution

In [1]:
function vowels(str) {
   // avoid same name with function, use array/ string?
  let vowel = ['a', 'e', 'i', 'o', 'u'];
  let counter = 0;

  for (let char of str.toLowerCase()){
    if (vowel.includes(char)){
      counter++;
    }    
  }

  return counter;
}

Alternative Solution

In [2]:
function vowels(str) {
  // g: do not stop at the first match, i: case insensitive
  const matches = str.match(/[aeiou]/gi)
  return matches ? matches.length : 0;
}
In [3]:
vowels('Hi There!')
Out[3]:
3
In [4]:
vowels('Why do you ask?')
Out[4]:
4
In [5]:
vowels('Why?')
Out[5]:
0